package com.zerox.controller;

import com.alibaba.fastjson.JSON;
import com.zerox.entity.SysDept;
import com.zerox.service.SysDeptService;
import com.zerox.uilt.UserListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("dept")
public class SysDeptController {


    @Autowired
    private SysDeptService sysDeptService;

    @GetMapping("todept")
    public String todept() {
        return "dept/dept";
    }

    @GetMapping("dept")
    @ResponseBody
    public String dept(@RequestParam(value = "deptName", required = false) String deptName, Integer pageIndex, Integer size) {
        List<SysDept> deptList = sysDeptService.list(deptName, pageIndex, size);
        int count = sysDeptService.count(deptName);

        UserListVO userListVO = new UserListVO(0, count, deptList, "");

        return JSON.toJSONString(userListVO);

    }

    @GetMapping("toadd")
    public String toadd() {
        return "dept/add";
    }

    @PostMapping(value = "deptadd", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String add(SysDept sysDept) {
        int row = sysDeptService.add(sysDept);

        return row > 0 ? "1" : "0";
    }

    @PostMapping("delete/{deptId}")
    @ResponseBody
    public String delete(@PathVariable("deptId") Integer deptId) {
        int row = sysDeptService.delete(deptId);

        return row > 0 ? "1" : "0";
    }

    @GetMapping("toupdate/{deptId}")
    public String toupdate(@PathVariable("deptId") Integer deptId, HttpServletRequest request) {
        SysDept sysDept = sysDeptService.selectById(deptId);
        request.setAttribute("sysDept", sysDept);

        return "dept/update";
    }

    @PostMapping("updatedept")
    @ResponseBody
    public String update(SysDept sysDept) {
        int row = sysDeptService.update(sysDept);
        return row > 0 ? "1" : "0";
    }
}
